<?php

header('Access-Control-Allow-Origin:*');
header('Content-Type:application/json');//加上这行,前端那边就不需要var result = $.parseJSON(data);

// 需要将 $wordPath 内容进行sql过滤 @todo
$wordPath = $_GET['wordPath'];
$savFileName = $_GET['savFileName'];
if ($wordPath && $savFileName) {
	# code...
	// 将文件下载到本地服务器,然后输出,输出后再将文件删除
	// 文件下载
	$url=$wordPath;  
	$save_dir = "down";  
	$filename =$savFileName;  //名称会改变
	$res = getFile($url, $save_dir, $filename,1);//0  1 都是好使的  
	
	// 文件输出
	$file_name = $savFileName;
	        $file_url=$_SERVER['DOCUMENT_ROOT'].'/download/down/'.$file_name;
		
	        if(file_exists($file_url)){
	            ob_clean();
	            $fp=fopen($file_url,"r");
	            $filesize=filesize($file_url);
	            header("Content-type:application/octet-stream");
	            header("Accept-Ranges:bytes");
	            header("Accept-Length:".$filesize);
	            header("Content-Disposition: attachment; filename=".$file_name);
	            $buffer=100024;
	            $buffer_count=0;
	            while(!feof($fp)&&$filesize-$buffer_count>0){
	                $data=fread($fp,$buffer);
	                $buffer_count+=$buffer;
	                echo $data;
	            }
	            fclose($fp);
				// 文件删除
				unlink($file_url);
	        } else{
	            echo "文件不存在";
	        }
	

}else{
	$ret = ["status" => 'fail',"msg" => '没有word文件地址或文件名称为空!'];
	echo json_encode($ret);
}

//页面编码要用gb2312
function getFile($url, $save_dir = '', $filename = '', $type = 0) {  
    if (trim($url) == '') {  
        return false;  
    }  
    if (trim($save_dir) == '') {  
        $save_dir = './';  
    }  
    if (0 !== strrpos($save_dir, '/')) {  
        $save_dir.= '/';  
    }  
    //创建保存目录  
    if (!file_exists($save_dir) && !mkdir($save_dir, 0777, true)) {  
        return false;  
    }  
    //获取远程文件所采用的方法  
    if ($type) {  
        $ch = curl_init();  
        $timeout = 5;  
        curl_setopt($ch, CURLOPT_URL, $url);  
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);  
        $content = curl_exec($ch);  
        curl_close($ch);  
    } else {  
        ob_start();  
        readfile($url);  
        $content = ob_get_contents();  
        ob_end_clean();  
    }  
    //echo $content;  
    $size = strlen($content);  
    //文件大小  
    $fp2 = @fopen($save_dir . $filename, 'a');  
    fwrite($fp2, $content);  
    fclose($fp2);  
    unset($content, $url);  
    return array(  
        'file_name' => $filename,  
        'save_path' => $save_dir . $filename,  
        'file_size' => $size  
    );  
}  